<template>
    <div class="my-business-opportunities-page">
        <!-- 页面标题 -->
        <van-nav-bar title="我的商机" left-arrow @click-left="goBack"  />
        <!-- 搜索区域 -->        <!-- 结果提示 -->
        <div v-if="opportunities && opportunities.length > 0 " style="padding:5px;background-color:#f7f7f7;">
            <div v-for="(sjinfo , index ) in opportunities" :key="index" style="margin-top:10px;background-color:#fff;padding:10px;" >
                <div class="info-section">
                    <div  @click="gotoSjinfo(sjinfo)">
                        <div class="title">{{sjinfo.sjtitle}}</div>
                        <div class="time">接单时间：{{formatDate(sjinfo.jdsj)}}</div>
                        <van-divider style="margin-top:10px;margin-bottom:10px;"/>
                        <div class="buyer">
                            <span style="color:#A399A3;font-size:15px;">采购人：</span>
                            <span style="color:black;font-size:15px;">{{sjinfo.cgrname}} {{ (sjinfo.provincename ? sjinfo.provincename:'') + '  ' + (sjinfo.cityname ? sjinfo.cityname:'') + '  ' + (sjinfo.areaname ? sjinfo.areaname:'') }}</span>
                        </div>
                        <div class="buyer">
                            <span style="color:#A399A3;font-size:15px;">联系方式：</span>
                            <span style="color:#FC0B00;font-size:15px;">{{sjinfo.cgrphone}}</span>
                        </div>
                        <div class="buyer">
                            <span style="color:#A399A3;font-size:15px;">商机价格：</span>
                            <span style="color:#FC0B00;font-size:15px;">{{ sjinfo.price }}元 / 条</span>
                        </div>
                        <div class="buyer">
                            <span style="color:#A399A3;font-size:15px;">支付状态：</span>
                            <span style="color:#FC0B00;font-size:15px;">{{ sjinfo.zfzt && sjinfo.zfzt == '1' ? '已支付':'未支付' }}</span>
                        </div>
                        <div style="display: flex; align-items: center;width:100%;margin-top:20px;">
                            <van-progress :percentage=" sjinfo.jdsl / sjinfo.zdsl * 100" color="#14C262" :stroke-width="14" :show-pivot="false" style="width: 85%;"/>
                            <span style="margin-left: 10px;width:15%;text-align:center;">{{ sjinfo.jdsl }} / {{sjinfo.zdsl}}</span>
                        </div>
                        <van-divider style="margin-top:15px;margin-bottom:5px;"/>
                        <div class="description">
                            {{ sjinfo.sjcontent ? sjinfo.sjcontent:'' }}
                        </div>
                    </div>
                    <!-- <div style="display: flex; justify-content: flex-end;margin-right:20px;" v-if="sjinfo.sszt == '0' ">
                        <van-button type="danger" @click="appeal(sjinfo)" size="small" >申诉</van-button>
                    </div> -->
                </div>
            </div>
        </div>
        <van-empty v-else description="暂无商机记录" /> 
        <!-- 后续可在此处添加商机列表展示的代码，目前无记录就只显示提示 -->
    </div>
</template>

<script>
import { addHyinfo, getAccessToken, getUserInfo, queryHyinfoByOpenid, queryOrderinfoList } from '../../api/api';
import wechat from '../../utils/wechat';
export default {
    data() {
        return {
            purchaseDate: '',
            remarkStatus: '',
            opportunities: [] ,// 用于存储商机数据，目前为空
            hyid:undefined,
            zhye:undefined,
            pageNum:1,
            pageSize:20,
            openid:undefined,
        };
    },
    created() {
        let that = this 
      // 在这里可以进行数据初始化或其他操作
        let openid = localStorage.getItem('openid')
        if(!openid){
            that.getWxopenid()
        }else{
            that.openid = openid
            that.queryHyinfoByOpenid()
        }
    },

    mounted() {
    // 可以在这里添加初始化逻辑
        window.addEventListener('scroll', this.handleScroll);
    },

    beforeDestroy() {
        // 移除滚动事件监听，防止内存泄漏
        window.removeEventListener('scroll', this.handleScroll);
    },

    methods: {
        handleScroll(){
            let that = this
            const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
            if (scrollTop + clientHeight >= scrollHeight -5 ) {
                that.pageNum = that.pageNum + 1;
                that.queryMyorder()
            }
        },

        gotoSjinfo(sjinfo){
            this.$router.push({
                path: '/home',
                query: {
                    sjid:sjinfo.sjid,
                    hyid:this.hyid,
                }
            })
        },

        getWxopenid(){
            let that = this
            wechat.getOpenId().then(data => {
                let code = data.code
                if (code) {
                    try {
                    let param = {
                        code: code,
                    }
                    getAccessToken(param).then(res => {
                        if(res.code == 200){
                        let access_token = res.data.access_token
                        let openid = res.data.openid
                        that.openid = openid
                        that.accessToken = access_token
                        localStorage.setItem('openid', res.data.openid)
                        let data2 = {
                            openid: openid,
                            access_token: access_token
                        }
                        getUserInfo(data2).then(res1 => {
                            if(res1.code == 200){
                            data2 = res1.data
                            that.saveHyinfoByOpenid(data2);
                            }
                        })
                        }
                    })
                    } catch (error) {
                    console.error('获取失败:', error);
                    }
                }
            })
            .catch(error => {
                debugger
                console.error('获取失败:', error)
            })
        },

            // 保存会员信息
        saveHyinfoByOpenid(param){
            let that = this
            param.wxname = param.nickname
            addHyinfo(param).then(response => {
                if(response.code == 200){           
                    that.hyid = response.data.hyid
                    that.zhye = response.data.zhye
                    localStorage.setItem('wxname', response.data.wxname)
                    localStorage.setItem('hyid', that.hyid)
                    localStorage.setItem('headimgurl', that.headimgurl)
                    that.queryMyorder()
                }else{
                console.log('添加失败:', response)
                }
            })
        },

        queryHyinfoByOpenid(){
            let that = this 
            let param = {openid:this.openid}
            queryHyinfoByOpenid(param).then(response => {
                if(response.code == 200){
                    if(response.data){
                        that.hyid = response.data.hyid
                        localStorage.setItem('hyid', that.hyid)
                        localStorage.setItem('wxname', response.data.wxname)
                        localStorage.setItem('headimgurl', that.headimgurl)
                        that.queryMyorder()
                    }else{
                        that.getWxopenid(param)
                    }
                
                }
            })
        },

        appeal(sjinfo){
            this.$router.push({
                path: '/orderappeal',
                query: {
                    hyid:this.hyid,
                    sjid:sjinfo.sjid,
                    cgrphone:sjinfo.cgrphone,
                    orderid:sjinfo.orderid
                }
            })
        },

        goBack() {
            // 处理返回上一页逻辑，比如使用路由返回
            this.$router.back()
        },

        padZero(num) {
            return num.toString().padStart(2, '0')
        },
        formatDate(dateStr) {
            const date = new Date(dateStr)
            const now = new Date()
            // 判断是否为今天
            if (date.getDate() === now.getDate() &&
                date.getMonth() === now.getMonth() &&
                date.getFullYear() === now.getFullYear()) {
                // 今天显示时分
                return `今天 ${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}`
            }
            // 非今天显示完整日期
            return `${date.getFullYear()}-${this.padZero(date.getMonth() + 1)}-${this.padZero(date.getDate())} 
                    ${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}`
        },

        queryMyorder(){
            let that = this 
            if(!this.hyid){
                return
            }
            let param = {
                hyid:this.hyid,pageNum:this.pageNum,pageSize:this.pageSize,zfzt:'1',
            }
            queryOrderinfoList(param).then(res=>{
                if(res.code == 200){
                    that.opportunities = that.pageNum == 1 ?   res.rows:that.opportunities.concat(res.rows)
                    console.log(that.opportunities)
                }
            })
        },
        searchOpportunities() {
            // 这里编写查询商机的逻辑，例如调用后端接口
            // 目前只是简单打印输入的值
            console.log('购买日期:', this.purchaseDate);
            console.log('备注状态:', this.remarkStatus);
        }
    }
};
</script>
    
<style scoped>
    .my-business-opportunities-page {
        background-color: #f7f7f7;
    }
    .search-area {
        display: flex;
        align-items: center;
    }
    .search-area van-field {
        flex: 1;
        margin-right: 10px;
    }
    .no-record-tip {
        text-align: center;
        color: #999;
        margin-top: 20px;
    }

        
    .order-page {
    padding: 5px;
    text-align: center;
    }
    .info-section {
        margin-bottom: 20px;
        border-bottom: #e4e7ed 1px solid;
        padding-bottom: 10px;;
        font-size: 15px;
    }

    .recharge-section {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;
    width:100%;
    font-size:15px;
    }
    .order-button-section {
    margin-bottom: 20px;
    }
    .tip-section {
    color: #999;
    margin-bottom: 10px;
    font-size: 15px;
    }
    .agreement-section {
    color: #999;
    font-size: 15px;
    }
    .equipment-inquiry {
    background-color: #ffffff;
    padding:10px;
    }
    .title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 5px;
    }
    .time{
    color: #b1b1b1;
    font-size:12px;
    }
    .buyer{
    margin-bottom: 10px;
    }
    .contact {
    margin-bottom: 5px;
    }
    .progress-text {
    float: right;
    }
    .limit-text {
    color: #999;
    margin-top: 5px;
    font-size: 13px;
    }

    .rownr {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    flex-direction: row;
    align-items: center;
    }
    .reached-limit {
    background-color: #e6f7ff;
    color: #1989fa;
    text-align: center;
    padding: 8px;
    border-radius: 4px;
    margin-top: 10px;
    }
    .description {
    padding: 5px;
    margin-top: 5px;
    line-height: 1.5;
    font-size: 14px;
    }
  </style>